package com.merak.rebot.controller;

import com.alibaba.fastjson.JSONObject;
import com.ctg.behavior.utils.ReturnUtil;
import com.merak.rebot.common.FileDirInfo;
import com.merak.rebot.common.PythonStatus;
import com.merak.rebot.config.MRebotsConfig;
import com.merak.rebot.core.MerakPythonEngine;
import com.merak.rebot.python.MerakPythonExecutor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/merak")
@CrossOrigin
public class MerakRebotController {
	
	@Autowired
	private MRebotsConfig mrebotsConfig;
	@Autowired
	private MerakPythonEngine merakPythonEngine;
	@Resource
	private MerakPythonExecutor merakPythonExecutor;

	@PostMapping("/echo")
	public String doRebot(@RequestBody String request) throws Exception {
		log.info(request);
		return request;
	}

	@GetMapping("/hello")
	public String hello() throws Exception {
		return "hello";
	}

	/*************************************
	 * 脚本清单
	 */
	@PostMapping("/script/list")
	public ReturnUtil pythonList() throws Exception {
		String queryName = "";
		String path = mrebotsConfig.getRebots().getPath();
		log.info("queryName:{}, path:{}", queryName, path);
		List<File> dirs = merakPythonExecutor.getFileDirs(queryName, path);
		List<FileDirInfo> fileDirInfoList = new ArrayList<>();
		for (int i = 0; i < dirs.size(); i++) {
			List<File> fileDirList1 = merakPythonExecutor.getFileDirInfoList(queryName, path, dirs, i, i+1+"", fileDirInfoList,dirs.get(i).getName(),"-1");
			for (int j = 0; j < fileDirList1.size(); j++) {
				List<File> fileDirList2 = merakPythonExecutor.getFileDirInfoList(queryName, path, fileDirList1, j, (i+1)+"-"+(j+1),fileDirInfoList.get(i).getChildren(),dirs.get(i).getName()+File.separator+fileDirList1.get(j).getName(),String.valueOf(i+1));
				for (int k = 0; k < fileDirList2.size(); k++) {
					merakPythonExecutor.getFileDirInfoList(queryName, path, fileDirList2, k, (i+1)+"-"+(j+1)+"-"+(k+1),fileDirInfoList.get(i).getChildren().get(j).getChildren(),dirs.get(i).getName()+File.separator+fileDirList1.get(j).getName()+File.separator+fileDirList2.get(k).getName(),(i+1)+"-"+(j+1));
				}
			}
		}
		//3.
		return ReturnUtil.success(fileDirInfoList);
	}

	/*************************************
	 * 脚本执行状态
	 */
	@PostMapping("/script/runStatus")
	public ReturnUtil pythonStatus(@RequestBody JSONObject jsonData) throws Exception {
//		String name = jsonData.getString("name");
		String fileDir = jsonData.getString("fileDir");
		List<PythonStatus> pythonLogs = new ArrayList<>();
		String path = mrebotsConfig.getRebots().getPath()+File.separator+fileDir;
		if(!(path.endsWith("\\") || path.endsWith("/"))) {
			path += File.separator;
		}
		if(StringUtils.isEmpty(fileDir)||!new File(path).exists()){
			return ReturnUtil.error("文件名称未填或者无该文件夹",pythonLogs);
		}
		merakPythonExecutor.selectLogsData(pythonLogs, path, null);
		return ReturnUtil.success(pythonLogs);
	}

	/*************************************
	 * 脚本执行状态及日志
	 */
	@PostMapping("/script/logs")
	public ReturnUtil pythonLogs(@RequestBody JSONObject jsonData) throws Exception {
		String name = jsonData.getString("name");
		String queryName = "";
		String path = mrebotsConfig.getRebots().getPath();
		log.info("queryName:{}, path:{}", queryName, path);
		List<File> dirs = merakPythonExecutor.getFileDirs(queryName, path);
//		String fileDir = jsonData.getString("fileDir");
		List<PythonStatus> pythonLogs = new ArrayList<>();
//		String path = mrebotsConfig.getRebots().getPath()+File.separator+fileDir;
		List<String> dirList = new ArrayList<>();
		for (File dir : dirs) {
			String childrenOne = path + File.separator + dir.getName();
			dirList.add(childrenOne);
			dirs = merakPythonExecutor.getFileDirs(queryName, childrenOne);
			for (File dir1 : dirs) {
				String childrenTwo = childrenOne + File.separator + dir1.getName();
				dirList.add(childrenTwo);
				dirs = merakPythonExecutor.getFileDirs(queryName, childrenTwo);
				for (File dir2 : dirs) {
					String childrenThree = childrenTwo + File.separator + dir2.getName();
					dirList.add(childrenThree);
				}

			}
		}
		for (String childrenPath : dirList) {
			if(!(childrenPath.endsWith("\\") || childrenPath.endsWith("/"))) {
				childrenPath += File.separator;
			}
			String logPath = childrenPath+File.separator + "logs" + File.separator;
			if(!new File(path).exists()){
				return ReturnUtil.error("无该文件夹",pythonLogs);
			}
			merakPythonExecutor.selectLogsData(pythonLogs, logPath,name);
		}
		pythonLogs = CollectionUtils.isEmpty(pythonLogs)?pythonLogs:pythonLogs.stream().sorted(Comparator.comparing(PythonStatus::getStartTime).reversed()).limit(mrebotsConfig.getRebots().getSelectMaxSize()).collect(Collectors.toList());
		return ReturnUtil.success(pythonLogs);
	}

	/*************************************
	 * 脚本执行动作===>必为异步
	 */
	@PostMapping("/script/exec")
	public ReturnUtil pythonExec(@RequestBody JSONObject jsonData) throws Exception {
		String fileDir = jsonData.getString("fileDir");
		String name = jsonData.getString("name");
		String param = jsonData.getString("param");
		log.info("name:{}", name);
		String scriptPath = mrebotsConfig.getRebots().getPath()+File.separator+fileDir;
		if(!(scriptPath.endsWith("\\") || scriptPath.endsWith("/"))) {
			scriptPath += File.separator;
		}
		String pythonParamName = scriptPath+name+".param";
		//第一步：在scriptPath下,生成param文件, 供Python脚本使用
		merakPythonExecutor.generateParamFile(pythonParamName,param);
		//第二步：执行Python脚本(必为异步)
		PythonStatus pythonStatus = merakPythonEngine.doExecutor(scriptPath, name);
		
		return ReturnUtil.success("脚本执行中...",pythonStatus);
	}
	
//	@GetMapping("/execute")
//	public String execute() throws Exception {
//		merakPythonExecutor.doExecutor("D:\\xuanxing\\python\\work", "pstart.bat", null);
//		return "success";
//	}

//	@GetMapping("/executeBackOff")
//	public String executeBackOff() throws Exception {
//		FileUtil.copyFile(new File("D:\\xuanxing\\python\\work\\resource" + File.separator + "pstart.bat"),
//				new File("D:\\xuanxing\\python\\work" + File.separator + "pstart.bat"));
//		return "success";
//	}

}
